<template>
  <div
    class="sidebarContainer"
    @click.stop
    :class="{ show: show, isDark: isDark }"
    :style="{ zIndex: zIndex }"
  >
    <span class="closeBtn el-icon-close" @click="close">x</span>
    <div class="sidebarHeader" v-if="title">
      {{ title }}
    </div>
    <div class="sidebarContent customScrollbar" ref="sidebarContent">
      <slot></slot>
    </div>
  </div>
</template>

<script setup>
import { ref, watch, onMounted, onBeforeUnmount } from 'vue'
import { storeToRefs } from 'pinia'
import { useMainStore } from '@/stores'
import { useEventBus } from '@/hooks'
import { store } from '@/config'

// 定义props
const props = defineProps({
  title: {
    type: String,
    default: ''
  }
})

// 响应式数
const sidebarContent = ref(null)
const show = ref(false)
const zIndex = ref(0)

// 使用store
const mainStore = useMainStore()
const { isDark } = storeToRefs(mainStore)

// 使用事件总线
const { $on, $off, $emit, $once } = useEventBus()

// 监听show变化
watch(show, (val, oldVal) => {
  if (val && !oldVal) {
    zIndex.value = store.sidebarZIndex++
  }
})

// 方法
const handleCloseSidebar = () => {
  close()
}

const close = () => {
  show.value = false
  mainStore.setActiveSidebar(null)
}

const getEl = () => {
  return sidebarContent.value
}

// 生命周期钩子
onMounted(() => {
  $on('closeSideBar', handleCloseSidebar)
})

onBeforeUnmount(() => {
  $off('closeSideBar', handleCloseSidebar)
})

// 暴露方法给父组件
defineExpose({
  show,
  close,
  getEl
})
</script>

<style lang="less" scoped>
.sidebarContainer {
  position: fixed;
  right: -300px;
  top: 110px;
  bottom: 0;
  width: 300px;
  background-color: #fff;
  border-left: 1px solid #e8e8e8;
  display: flex;
  flex-direction: column;
  transition: all 0.3s;

  &.isDark {
    background-color: #262a2e;
    border-left-color: hsla(0, 0%, 100%, 0.1);

    .sidebarHeader {
      border-bottom-color: hsla(0, 0%, 100%, 0.1);
      color: #fff;
    }

    .closeBtn {
      color: #fff;
    }
  }

  &.show {
    right: 0;
  }

  .closeBtn {
    position: absolute;
    right: 20px;
    top: 12px;
    font-size: 20px;
    cursor: pointer;
  }

  .sidebarHeader {
    width: 100%;
    height: 44px;
    border-bottom: 1px solid #e8e8e8;
    display: flex;
    justify-content: center;
    align-items: center;
    flex-grow: 0;
    flex-shrink: 0;
  }

  .sidebarContent {
    width: 100%;
    height: 100%;
    overflow: auto;
  }
}
</style>
